package main

import (
	"flag"
	"io"
	"log"
	"os"
	"os/exec"
	"runtime"
)

var startFlag = flag.Bool("start", false, "start all")
var stopFlag = flag.Bool("stop", false, "stop all")

func Start(appName, workDir string, logFile io.Writer) {
	cmd := exec.Command(appName)
	cmd.Dir = workDir
	cmd.Stderr = logFile
	cmd.Stdout = logFile
	cmd.Start()
}

func PKill(appName, workDir string, logFile io.Writer) {
	cmd := exec.Command("pkill", appName)
	cmd.Dir = workDir
	cmd.Stderr = logFile
	cmd.Stdout = logFile
	cmd.Start()
}

func main() {
	flag.Parse()

	var logPath string = "dorSvrAutorun.log"
	if runtime.GOOS == "linux" {
		logPath = "/var/log/" + logPath
	}
	f, errT := os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)

	if errT == nil {
		defer f.Close()
		log.SetOutput(f)
	}
	log.Println("dorSvrAutorun.")

	workDir := "/usr/prjs/gocode/bin"

	if *startFlag {
		log.Println("start.")
		Start(workDir+"/gDataServer", workDir, f)
		Start(workDir+"/statistics_server", workDir, f)
		Start(workDir+"/server_main", workDir, f)
	}

	if *stopFlag {
		log.Println("stop.")
		PKill("gDataServer", workDir, f)
		PKill("statistics_ser", workDir, f)
		PKill("server_main", workDir, f)
	}
}
